package org.ykh.gmall.web.all.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.ykh.gmall.feign.product.client.ProductFeignClient;
import org.ykh.gmall.result.Result;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

@Controller
@SuppressWarnings("all")
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 首页显示数据
     * @return
     */
    @GetMapping({"/","/index.html","*"})
    public String index(Model model){
        //获取三级分类数据
        Result<List> baseCategoryList = productFeignClient.getBaseCategoryList();
        //设置数据
        model.addAttribute("list",baseCategoryList.getData());

        return "index/index";
    }

    /**
     * 页面生成,Niginx部署
     * @return
     */
    @GetMapping("/createIndex")
    @ResponseBody
    public Result createIndex(){


        //远程请求获取分类数据
        Result<List> baseCategoryList = productFeignClient.getBaseCategoryList();
        //设置数据上下文对象
        Context context=new Context();
        //设置数据
        context.setVariable("list",baseCategoryList.getData());
        FileWriter fileWriter= null;
        try {
            fileWriter = new FileWriter("D:\\demo\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //生成指定页面
        templateEngine.process("index/index.html",context,fileWriter);

        return Result.ok("页面生成成功！！");
    }
}
